package ntu.metaweb.storage;

import java.util.HashSet;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class User {
	private String name;
	private String email;
	private String encryptedPassword;
	private HashSet<String> trustedUsers;
	private HashSet<String> trusterUsers;
	
	public User(String name, String email, String password) {
		this.name = name;
		this.email = email;
		this.trustedUsers = new HashSet<String>();
		this.trusterUsers = new HashSet<String>();
		try {
			this.encryptedPassword = URLEncoder.encode(SHA1(password), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public String getName() {
		return this.name;
	}
	
	public String getEmail() {
		return this.email;
	}
	
	public boolean authenticate(String password) {
		try {
			String encrypted = URLEncoder.encode(SHA1(password), "UTF-8");
			System.out.println(encrypted + " " + this.encryptedPassword);
			return this.encryptedPassword.equals(encrypted);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return false;
	}
	
	public HashSet<String> getTrustedUsers() {
		return this.trustedUsers;
	}
	
	public HashSet<String> getTrusterUsers() {
		return this.trusterUsers;
	}
	
	private String SHA1(String password) {
		MessageDigest md;
		try {
			md = MessageDigest.getInstance("SHA-1");
			byte[] sha1hash = new byte[40];
			md.update(password.getBytes("iso-8859-1"), 0, password.length());
	    sha1hash = md.digest();
	    return new String(sha1hash);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public int hashCode() {
		return this.name.hashCode();
	}
	
	public boolean equals(Object o) {
		if (!(o instanceof User)) {
			return false;
		} else {
			User user = (User) o;
			return this.name.equals(user.name);
		}
	}
}
